<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>配方管理</title>
    <meta name="keywords" content="">
    <meta name="description" content="">
    <link rel="shortcut icon" th:href="@{/favicon.ico}">
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/font-awesome.css}" rel="stylesheet">
    <link th:href="@{/css/animate.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
    <link th:href="@{/self/self-common.css}" rel="stylesheet">

    <link th:href="@{/css/plugins/bootstrap-table/bootstrap-table.min.css}" rel="stylesheet">
    <link th:href="@{/css/plugins/bootstrap-select/bootstrap-select.css}" rel="stylesheet">

    <!-- Sweet Alert -->
    <link th:href="@{/css/plugins/sweetalert/sweetalert.css}" rel="stylesheet">
</head>

<body class="gray-bg" id="layDate">

<div class="wrapper wrapper-content animated fadeInRight">

    <div class="row">
        <!--查询区域-->
        <div class="col-sm-12 search-card">
            <div class="ibox">
                <div class="ibox-content">

                    <form class="form-inline">
                        <div class="form-group searchCX">
                            <input id="searchName" class="form-control" type="text" placeholder="请输入产品名称" clearable>
                        </div>

                        <div class="form-group searchCX">
                            <input id="searchSn" class="form-control" type="text" placeholder="请输入产品编号" clearable>
                        </div>
                        <div class="form-group searchCX">
                            <input id="searchBatch" class="form-control" type="text" placeholder="请输入产品批次" clearable>
                        </div>

                        <div class="form-group">
                            <button id="btnSearch" class="btn btn-purple" type="button" onclick="querySearch()">
                                <i class="fa fa-search"></i>
                                查询
                            </button>
                        </div>
                    </form>

                </div>
            </div>
        </div>

        <div class="col-sm-12 table-card">
            <div class="ibox">
                <div class="ibox-title">
                    <h5>
                        <i class="fa fa-bookmark"></i>
                        称料工单管理
                    </h5>
                </div>
                <div class="ibox-content">

                    <table id="dataTable" data-mobile-responsive="true"></table>
                </div>
            </div>
        </div>
        <div class="col-sm-12 table-card a">
            <div class="ibox-content ">


                    <div id="toolbar" style="display: none">
                        <form class="form-inline btnOpacity">
                            <div class="btn-group">
                                <button class="btn btn-purple" type="button" data-toggle="modal"
                                        data-target="#myModal">
                                    <i class="fa fa-plus-circle"></i>
                                    新增
                                </button>
                            </div>
                            <div class="form-group">
                                <button id="importBtn" class="btn btn-purple" type="button" data-toggle="modal" data-target="#myModal1">
                                    <i class="fa fa-upload"></i>
                                    导入
                                </button>
                            </div>
<!--                            <div class="form-group">-->
<!--                                <button id="export" class="btn btn-orange" type="button">-->
<!--                                    <i class="fa fa-download"></i>-->
<!--                                    导出-->
<!--                                </button>-->
<!--                            </div>-->

                        </form>
                    </div>
                    <table id="recipeTable" data-mobile-responsive="true"></table>
                </div>
            </div>
        </div>


    <!--    新增-->
    <div class="modal inmodal fade" id="myModal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">新增配方原料</h4>
                    <button type="button" class="close" data-dismiss="modal">×</button>
                </div>
                <div class="modal-body">

                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="col-sm-3 control-label">原料：</label>
                            <div class="col-sm-7">
                                <input id="stock" type="text" name="" class="form-control"
                                       ondblclick="SelectStock()"
                                       placeholder="双击选择原料">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">占比（%）：</label>
                            <div class="col-sm-7">
                                <input id="rate" type="text" name="" class="form-control"
                                       placeholder="请输入占比">
                            </div>
                        </div>


                        <div class="form-group">
                            <label class="col-sm-3 control-label">误差值（kg）：</label>
                            <div class="col-sm-7">
                                <input id="errorNumber"  value="2" type="text" name="" class="form-control"
                                       placeholder="请输入误差值">
                            </div>
                        </div>



                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-white btn-close" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-purple btn-save" id="btnSave">保存</button>
                </div>
            </div>
        </div>
    </div>





        <!--导入模态框-->
        <div class="modal inmodal fade" id="myModal1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">配方导入</h4>
                        <button type="button" class="close" data-dismiss="modal" onclick="removeImp()">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="col-md-12">
                            <div class="form-group">
                                <div class="import_btn" style="width:100%;text-align:left">
                                    <label for="import"><span>选择文件</span></label>
                                    <span id="fileName">未上传文件</span>
                                </div>
                                <input type="file" id="import" onchange="loadFile(this.files[0])" name="import"
                                       style="width: 220px;opacity:0">
                            </div>
                            <div class="form-group">
                                <a class="downtele" style="text-align:left;" href="#" onclick="downLoadTemp();"><span
                                        style="padding:5px ;font-size:16px;font-weight:200;color:#337ab7">模板下载</span></a>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-close" data-dismiss="modal"
                                onclick="removeImp()">取消
                        </button>
                        <button type="button" class="btn btn-purple btn-save" id="btnSaveExl" onclick="mySubmit()">保存
                        </button>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- 全局js -->
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/js/content.js}"></script>
<script th:src="@{/js/app.js}"></script>

<!-- Bootstrap table -->
<script th:src="@{/js/plugins/bootstrap-table/bootstrap-table.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table/bootstrap-table-mobile.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js}"></script>
<!--bootstrap导出-->
<script th:src="@{/self/tableExport.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table-export/bootstrap-table-export.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table-export/tableExport.js}"></script>
<!--下拉选择框-->
<script th:src="@{/js/plugins/bootstrap-select/bootstrap-select.js}"></script>
<!--提示框-->
<script th:src="@{/js/plugins/layer/layer.min.js}"></script>
<!--日期-->
<script th:src="@{/js/plugins/layer/laydate/laydate.js}"></script>
<!-- Sweet Alert -->
<script th:src="@{/js/plugins/sweetalert/sweetalert.min.js}"></script>

<script>



    var productSn='';
    var productName='';
    var productBatch='';

    var productId=''
    var  stockId='';


    //新增/更新标志位
    var addOrUp=0

    // var productId=0;

    // $(".a").hide()

    /*查询*/
    function querySearch() {
        productSn=$.trim($("#searchSn").val());
        productName=$.trim($("#searchName").val());
        productBatch=$.trim($("#searchBatch").val());

        $('#dataTable').bootstrapTable('refresh');
        productSn='';
        productName='';
        productBatch='';
    }

    /*dataTable*/
    $(document).ready(function () {
        function queryParams(params) {
            return {
                pageSize: params.pageSize,
                pageNumber: params.pageNumber,
                productSn: productSn,
                productName:productName,
                productBatch:productBatch
            }
        }

        $('#dataTable')
            .bootstrapTable({
                url: baseUrl + "getProductPageInfo",
                method: "post",
                queryParamsType: "",
                queryParams: queryParams,
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                striped: false, //是否显示行间隔色
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                search: false, //是否显示搜索框功能
                pagination: true, //是否分页
                showRefresh: false, //是否显示刷新功能
                showToggle: false,
                showColumns: false,
                // clickToSelect: true, //是否启用点击选中行
                // clickToSelect: true, //是否启用点击选中行
                // uniqueId: "indentId", //每一行的唯一标识，一般为主键列
                // idField: "indentId",
                formatSearch: function () {
                    return "";
                },
                iconSize: 'outline',
                sidePagination: "server", //服务端请求
                showExport: false,//显示导出按钮
                buttonsAlign: "right",  //按钮位置
                exportTypes: ['excel'],  //导出文件类型
                pageList: [10, 20, 30, 'all'],
                exportDataType: "basic",//导出类型 'basic':当前页, 'all', 'selected'.
                // toolbar: '#toolbar', //工具按钮用哪个容器
                icons: {
                    refresh: 'glyphicon-repeat',
                    toggle: 'glyphicon-list-alt',
                    columns: 'glyphicon-list',
                    export: 'glyphicon-export'
                }
                , responseHandler: function (res) {
                    var rows = [];
                    if (res.total !== 0) {
                        rows = res.list;
                    }
                    var result = {
                        rows: rows,
                        total: res.total
                    };
                    return result;
                },
                onEditableSave: function (field, row, oldValue, $ele) {
                    //更新数据到数据库
                },
                columns: [{
                    field: 'productSn',
                    title: '产品编号',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        } else {
                            return value;
                        }
                    }
                }, {
                    field: 'productName',
                    title: '产品名称',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        } else {
                            return value;
                        }
                    }
                }, {
                    field: 'abbreviation',
                    title: '简称',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        } else {
                            return value;
                        }
                    }
                }, {
                    field: 'productBatch',
                    title: '批次号',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        } else {
                            return value;
                        }
                    }
                },
                    {
                        field: 'productShape',
                        title: '性状',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return '';
                            } else {
                                return value;
                            }
                        }
                    },

                    {
                        field: 'manufactureDate',
                        title: '制造日期',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return '';
                            } else {
                                return value;
                            }
                        }
                    },

                    ],

                onClickRow: function (row, $element) {
                    $('.info').removeClass('info');
                    $($element).addClass('info');
                    $("#toolbar").attr("style","display:block")
                    $('#recipeTable').bootstrapTable('destroy');
                    productId=row.id
                    showRecipeDetail(row.id)
                    // $(".a").show()

                }
            });

        function showRecipeDetail(order_weight_id) {
            function queryParams1(params) {
                return {
                    pageSize: params.pageSize,
                    pageNumber: params.pageNumber,
                    productId: order_weight_id
                }
            }

            $('#recipeTable')
                .bootstrapTable({
                    url: baseUrl + "getRecipePageInfo",
                    method: "post",
                    queryParamsType: "",
                    queryParams: queryParams1,
                    pageNumber: 1, //初始化加载第一页，默认第一页
                    pageSize: 10, //每页的记录行数（*）
                    striped: false, //是否显示行间隔色
                    cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    search: false, //是否显示搜索框功能
                    pagination: true, //是否分页
                    showRefresh: false, //是否显示刷新功能
                    showToggle: false,
                    showColumns: false,
                    // clickToSelect: true, //是否启用点击选中行
                    // uniqueId: "indentId", //每一行的唯一标识，一般为主键列
                    // idField: "indentId",
                    formatSearch: function () {
                        return "";
                    },
                    iconSize: 'outline',
                    sidePagination: "server", //服务端请求
                    showExport: false,//显示导出按钮
                    buttonsAlign: "right",  //按钮位置
                    exportTypes: ['excel'],  //导出文件类型
                    pageList: [10, 20, 30, 'all'],
                    exportDataType: "basic",//导出类型 'basic':当前页, 'all', 'selected'.
                    toolbar: '#toolbar', //工具按钮用哪个容器
                    icons: {
                        refresh: 'glyphicon-repeat',
                        toggle: 'glyphicon-list-alt',
                        columns: 'glyphicon-list',
                        export: 'glyphicon-export'
                    }
                    , responseHandler: function (res) {
                        console.log(res)
                        var rows = [];
                        if (res.total !== 0) {
                            rows = res.list;
                        }
                        var result = {
                            rows: rows,
                            total: res.total
                        };
                        return result;
                    },
                    onEditableSave: function (field, row, oldValue, $ele) {
                        //更新数据到数据库
                    },
                    columns: [
                        {
                            field: 'stockSn',
                            title: '原料编号',
                            formatter:function (value, row, index){
                                if (value==null)
                                    return ''
                                else {
                                    return value
                                }
                            }
                        },
                        {
                            field: 'stockName',
                            title: '原料名称',
                            formatter:function (value, row, index){
                                if (value==null)
                                    return ''
                                else {
                                    return value
                                }
                            }
                        },
                        {
                            field: 'stockTypeName',
                            title: '原料类型',
                            formatter:function (value, row, index){
                                if (value==null)
                                    return ''
                                else {
                                    return value
                                }
                            }
                        },
                        {
                            field: 'rate',
                            title: '占比(%)',
                            formatter: function (value, row, index) {
                                if (value==null){
                                    return ''
                                }
                                if (value > 100  && row.id==-1) {
                                    return '<span style="color:#ff0000">' + '合计 '+ value + '</span>';
                                } else  if (row.id==-1){
                                    return '<span >' + '合计 '+ value + '</span>';
                                }
                                else {
                                    return value
                                }
                            }
                        },
                        {
                            field: 'errorNumber',
                            title: '误差值（kg）',
                            formatter:function (value, row, index){
                                if (value==null)
                                    return ''
                                else {
                                    return value
                                }
                            }

                        },

                        {
                            field: 'operation',
                            title: '操作',
                            align: 'center',
                            width: '100',
                            formatter: function (value, row, index) {
                                var startBtn = "<button type='button' class = 'btn btngroup btn-xs czIcon icon_edit' onclick='editRecipe(\"" + row.id + "\",\"" + row.stockName + "\",\"" + row.rate + "\",\"" + row.errorNumber + "\",\"" + row.stockId + "\")' title='编辑'></button>";
                                var closeBtn = "<button type='button' class = 'btn btngroup btn-xs czIcon icon_close'  onclick='deleteRecipe(\"" + row.id + "\")' title='删除'></button>";
                                if (row.id!=-1){
                                    return startBtn + closeBtn;
                                }
                                else
                                    return ''

                            }
                        }

                    ],
                });
        }

    });



    //弹窗，数据置空
    $("#myModal").on("hidden.bs.modal", function () {
        $("#stock").val("");
        $("#rate").val("");
    });


    var updateId=''
    //打开编辑弹窗
    function editRecipe(recipeId,stockName,rate,errorNumber,stock_id) {
        addOrUp=1;
        updateId = recipeId
            stockId=stock_id
            $("#stock").val(stockName);
            $("#rate").val(rate);
            $("#errorNumber").val(errorNumber);


        //打开弹窗
        $("#myModal").modal('show');

    }




    //保存按钮
    $("#btnSave").click(function () {
        var rate = $("#rate").val();
        var  errorNumber=$("#errorNumber").val();
        if (!validate(rate)) {
            layer.msg("占比必须输入正数")
            return
        }
        if (rate>100) {
            layer.msg("占比不能大于100！")
            return
        }
        if (!stockId) {
            layer.msg("请选择原料")
            return
        }
        if (!errorNumber){
            layer.msg("请输入误差值")
            return
        }

        if (!validate(errorNumber)){
            layer.msg("误差值请输入正数")
            return
        }
       if(addOrUp==0){
           PostWebApi("addRecipe", {
               stockId: stockId,
               productId: productId,
               rate: rate,
               errorNumber: errorNumber,
           }).done(function (data) {
               if (data.code === 0) {
                   $("#myModal").modal('hide');
                   layer.msg(data.msg)
                   $('#recipeTable').bootstrapTable('refresh');
               } else {
                   layer.msg(data.msg);
               }
           });
       }
        if(addOrUp==1){
            PostWebApi("updateRecipe", {
                stockId: stockId,
                productId: productId,
                rate: rate,
                errorNumber: errorNumber,
                id:updateId
            }).done(function (data) {
                if (data.code === 0) {
                    $("#myModal").modal('hide');
                    layer.msg(data.msg)
                    $('#recipeTable').bootstrapTable('refresh');
                } else {
                    layer.msg(data.msg);
                }
            });
        }
    });



    //删除配方中的原料
    function deleteRecipe(recipeId) {
        swal({
            title: "您确定要删除该条数据吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "取消",
            confirmButtonColor: "rgb(85 221 218)",
            confirmButtonText: "确定",
            closeOnConfirm: false
        }, function () {
            swal.close();
            PostWebApi("deleteRecipe", {id: recipeId}).done(function (data) {
                if (data.code == "0") {
                    $("#recipeTable").bootstrapTable('refresh');
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            })
        })
    }





    //----------------------------EXCEL-------------------------------------
    // 使用tableExport.js导出数据
    $("#export").click(function () {
        $('#dataTable').tableExport(
            {
                type: 'excel',//导出excel
                escape: 'false',
                ignoreColumn: [13],  //忽略某一列的索引
                fileName: '工单信息',  //文件名称设置
                worksheetName: '工单信息',  //表格工作区名称
                tableName: '工单信息',
                excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
            }
        )
    })

    //下载导入模版
    function downLoadTemp(){
        window.location.href =baseUrl + "downRecipeExcelTemplate?fileName=配方导入模版";
    }

    //移除文件文字
    function removeImp() {
        var file = document.getElementById('import');
        file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值
        //或者
        //file.outerHTML = file.outerHTML; //重新初始化了file的html
        $("#fileName").html('未上传文件');
    }

    //加载文件名
    function loadFile(file) {
        $("#fileName").html(file.name);
    }

    //导入excel文件信息
    function mySubmit() {
        var file = document.getElementById("import").files[0];
        var fileName = $("#fileName").val();
        var preffix = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf("."));
        var suffix = fileName.substring(fileName.lastIndexOf("."));
        //创建新的表单数据对象
        var formData = new FormData();
        formData.append("file", file);
        formData.append("preffix", preffix);
        formData.append("suffix", suffix);
        $.ajax({
            url: baseUrl + "recipeImport",
            type: "POST",
            contentType: false,
            datatype: "text",
            data: formData,
            processData: false, // 告诉jQuery不要去处理发送的数据
            success: function (data) {
                $('#recipeTable').bootstrapTable('refresh');
                layer.msg(data.msg)
            }
        });
        removeImp();
        $('#myModal1').modal('hide');
        return false;
    }










    // 选择原料
    function SelectStock() {
        var index = layer.open({
            type: 2,
            title: "选择原料",
            shadeClose: false,
            shade: 0.4,
            area: ['1050px', '700px'],
            content: '/dazhi/view/select_stock',
            btn: ['确定', '关闭'],
            yes: function (index) {
                var res = window["layui-layer-iframe" + index].submit();
                if (res != "") {
                    layer.close(index);
                    var data = $.parseJSON(res)
                    $("#stock").val(data.stockName);
                    stockId = data.stockId;
                }

            }
        });
    }


    //判断输入框中的值是否为正数
    function validate(num) {
        var reg = /^[0-9]\d*(\.\d+)?$/
        if (reg.test(num)) return true;
        return false;
    }



</script>

<!--高级操作-->
<script>
    function openSeniorCon() {
        $("#seniorCon").toggle();
    }

    //----------------------------------------------------------------------------
    // 使用tableExport.js导出数据
    $("#export").click(function () {
        $('#dataTable').tableExport(
            {
                type: 'excel',//导出excel
                escape: 'false',
                ignoreColumn: [0],  //忽略某一列的索引
                fileName: '导出文件',  //文件名称设置
                worksheetName: 'sheet1',  //表格工作区名称
                tableName: '导出文件',
                excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
            }
        )
    })

</script>

<!--laydate-->
<script>
    laydate({
        elem: '#layDate .dateTime', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
        event: 'focus' //响应事件。如果没有传入event，则按照默认的click
    });
</script>


</body>

</html>
